import appconfig 
from google.appengine.api import users
from string import Template

# html template string
def html(filename):
    str = ''
    myfile = open(filename, "r")
    for line in myfile.readlines():
        str += line
    myfile.close()
    return str


# html header string
def header():
    temp = html("header.html")
    tpl = Template(temp)
    return tpl.substitute(logout_url=users.create_logout_url("/"))


# html footer string
def footer():
    return html("footer.html")


# html about string
def about():
    return html("about.html")


# html config string
def config_form():
    temp = html("config.html")
    cfg = appconfig.get_all()
    return temp%(cfg['twitter_username'], 
            cfg['twitter_password'],
            cfg['twitter_url'],
            cfg['minicloud_username'],
            cfg['minicloud_password'],
            cfg['minicloud_url'])


# html tweets
def tweets(tweets):
    if isinstance(tweets, dict):
        return error(tweets["error"])
    temp = "<span class='border-table-title'>Latest 20 Tweets:</span>\
            <table class='border-table'><tr>\
            <th>ID</th>\
            <th width='120'>TIME</th>\
            <th width='400'>TEXT</th>\
            </tr>"
    for twt in tweets:
        temp += "<tr>"\
                + "<td>" + str(twt["id"]) + "</td>"\
                + "<td>" + twt["created_at"] + "</td>"\
                + "<td>" + twt["text"] + "</td>"\
                + "</tr>"
    temp += "</table>"
    return header() + temp + footer()


# html error
def error(msg):
    body = "<p class='error'>%s</p>"%msg
    return header() + body + footer()


# html minicloud
def minicloud():
    temp = "<div>\
            <span style='font-size: 14px;'>Input text and update to minicloud:</span>\
            <form name='miniform' method='post' action='/update'>\
            <textarea name='text'></textarea>\
            <a class='cfg-button-bg' style='margin-left: 340px;' href='javascript: document.miniform.submit();'>Update</a>\
            </form>\
            </div>"
    return temp


# html log
def log(tweets):
    temp = "<span class='border-table-title'>Latest 20 Logs:</span>\
            <table class='border-table'><tr>\
            <th>ID</th>\
            <th width='120'>TIME</th>\
            <th width='400'>TEXT</th>\
            <th width='30'>LOG_FLAG</th>\
            <th widht='150'>LOG_MSG</th>\
            </tr>"
    for twt in tweets:
        temp += "<tr>"\
                + "<td>" + str(twt.id) + "</td>"\
                + "<td>" + str(twt.time) + "</td>"\
                + "<td>" + twt.text + "</td>"\
                + "<td>" + str(twt.log_flag) + "</td>"\
                + "<td>" + twt.log_msg + "</td>"\
                + "</tr>"
    temp += "</table><br>\
            <span><a href='clear'>Clear Logs</a></span>"
    return temp
